#!/usr/bin/env python
from argparse import ArgumentParser
import pyranges as pr
from methplotlib.differential.differential import main
from methplotlib.helpers import methylation_pyranges_from_csv


def get_args():
    parser = ArgumentParser(
        description="Check for modification differences using fisher exact test.")
    parser.add_argument(
        "-b", "--bed", help="Bed file to aggregate modifications on.", required=True)
    parser.add_argument("-A", "--Agroup", nargs='+', help="Frequencies of group A.")
    parser.add_argument("-B", "--Bgroup", nargs='+', help="Frequencies of group B.")
    parser.add_argument("-c", "--cutoff", help="FDR cutoff. Default: 0.05",
                        default=0.05, type=float)
    parser.add_argument(
        "-o", "--out", help="File to write results to. Default: stdout.", default="-")
    return parser.parse_args()


if __name__ == '__main__':

    args = get_args()

    a_range = pr.concat([methylation_pyranges_from_csv(f) for f in args.Agroup])
    b_range = pr.concat([methylation_pyranges_from_csv(f) for f in args.Bgroup])
    bed = pr.read_bed(args.bed).merge()

    gr = main(a_range, b_range, bed)

    gr = gr[gr.ORFDR <= args.cutoff]

    if args.out == "-":
        import sys
        gr.to_csv(sys.stdout, sep="\t")  # index=False)
    else:
        from pathlib import Path

        p = Path(args.out)
        Path.mkdir(p.parent, exist_ok=True, parents=True)

        gr.to_csv(str(p), sep="\t")
